<template>
  <div style="">
    <div id="js-canvas"></div>
    <div id="js-properties-panel"></div>
    <div>
      <a-button @click="download">保存到本地</a-button>
      <button @click="createNew">新建</button>
    </div>
    <!-- <a-modal></a-modal> -->
  </div>
</template>
<script>
  import BpmnModdle from 'bpmn-js/lib/Modeler';
  import diagramXml from '../../../assets/diagram.bpmn'; //xml文件
  import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';

  export default {
    name: 'bpmn',
    data() {
      return {
        viewer: null,
        canvas: null,
        bpmnText: '',
      }
    },
    mounted() {
      this.$nextTick().then(() => {

        this.canvas = document.getElementById('js-canvas')

        this.viewer = new BpmnModdle({
          container: this.canvas,
          keyboard: {
            bindTo: window
          },
          propertiesPanel: {
            parent: '#js-properties-panel'
          },
          additionalModules: [
            propertiesProviderModule
          ]
        })
        this.create()
      })
    },
    methods: {
      download() {
        this.viewer.saveXML({ format: true }, (err, xml) => {
          if (xml) {
            this.bpmnText = xml
            var a = document.createElement('a');
            a.href = 'data:application/bpmn20-xml;charset=UTF-8,' + encodeURIComponent(xml)
            a.download = 'diagram.bpmn';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            a = null;
          }

        })
      },
      create() {
        this.bpmnText = diagramXml
        this.viewer.importXML(diagramXml, err => {
          if (err) {
            throw (err)
          }
          this.viewer.get('canvas').zoom('fit-viewport')
          var eventBus = this.viewer.get('eventBus');

          var events = [
            'element.click',
            'element.dblclick'
          ]
          events.forEach(event => {
            eventBus.on(event, (e) => {
            })
          })
        })

      },
      createNew() {
        this.viewer.createDiagram(err => {
          if (err) {
            throw (err)
          }
          this.viewer.get('canvas').zoom('fit-viewport')
          var eventBus = this.viewer.get('eventBus');

          var events = [
            'element.click',
            'element.dblclick'
          ]
          events.forEach(event => {
            eventBus.on(event, (e) => {
              // console.log(event, 'on', e.element.id)
            })
          })
        })
      }
    }
  }
</script>
<style>
  /*引入样式，否则显示不出内容*/
  @import 'bpmn-js/dist/assets/diagram-js.css';
  @import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
  @import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
  @import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
  @import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';
</style>
